<!--
*Author：富行天下团队
 *
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/mall/Mall_good.js此处编写
 -->
<template>
<div class="divSea" v-loading="loading">
  <div class="block">
    <el-date-picker v-model="times" type="daterange" range-separator="至" size="small" :picker-options="pickerOptions" start-placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" end-placeholder="结束日期" @change="getList"></el-date-picker>
    <el-button type="primary" size="small" @click="getList">查询</el-button>
    <el-button type="success" size="small" @click="dialogVisible = true">添加</el-button>
    <el-button type="warning" size="small" @click="exportToExcel">导出</el-button>
  </div>
  <div class="tableDiv" v-if="tableData.length"> 
    <!-- width="120" -->
    <el-table :data="tableData" border style="width: 100%;" height="100%" :span-method="objectSpanMethod" show-summary :summary-method="getSummaries" :row-class-name="tableRowClassName">
      <el-table-column prop="sort" label="序号" fixed width="50" align="center"></el-table-column>
      <el-table-column prop="project" label="项目类别" fixed width="120"></el-table-column>
      <el-table-column prop="name" label="项目" fixed width="120"></el-table-column>
      <el-table-column prop="amount" label="金额" width="100"></el-table-column>
      <el-table-column prop="douYin" label="抖音" width="100"></el-table-column>
      <el-table-column prop="xiaoChengXu" label="小程序" width="100"></el-table-column>
      <el-table-column prop="huiDian" label="汇点" width="100"></el-table-column>
      <el-table-column prop="meiTuan" label="美团" width="100"></el-table-column>
      <el-table-column prop="xieCheng" label="携程" width="100"></el-table-column>
      <el-table-column prop="ningMeng" label="柠檬" width="100"></el-table-column>
      <el-table-column prop="naiSi" label="奈斯" width="100"></el-table-column>
      <el-table-column prop="zhiKeTong" label="直客通" width="100"></el-table-column>
      <el-table-column prop="weiTian" label="维天"></el-table-column>
      <el-table-column prop="lengShan" label="冷山"></el-table-column>
      <el-table-column prop="linSheng" label="林盛"></el-table-column>
      <el-table-column prop="linXi" label="霖希"></el-table-column>
      <!-- <el-table-column prop="amount14" label="卡类别"></el-table-column>
      <el-table-column prop="amount15" label="数量"></el-table-column> -->
      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
        <el-button @click="handleClick(scope)" type="text" size="small" v-if="['6','7','8','9'].indexOf(scope.row.sort)!=-1 && scope.row.name!='小计' && scope.row.name!='牛肉面'">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog title="新增" :close-on-click-modal="false" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
    <div>
      <el-form :model="form" v-show="itemShow">
        <el-form-item label="项目类别">
          <el-select v-model="form.type" placeholder="请选择项目类别">
            <el-option label="联营" :value="1"></el-option>
            <el-option label="赛事服务费/广告费等" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :model="formTable" ref="ruleForm" v-show="!itemShow" label-width="100px">
        <el-form-item label="项目类别">
          {{{1:'联营',2:'赛事服务费/广告费等'}[form.type]}}
        </el-form-item>
        <div v-for="(item,index) in tableHeadForm" :key="index" class="container">
          <el-form-item :label="item.title" :prop="item.key"  :rules="[{ required: true, message: `请输入${item.title}`, trigger: 'blur' },]">
            <el-input-number v-model.trim="formTable[item.key]" size="small" controls-position="right" :precision="2" :min="0" v-if="item.type=='number'" :placeholder="'请输入'+item.title"></el-input-number>
            <el-input v-model.trim="formTable[item.key]" size="small" :placeholder="'请输入'+item.title" v-else></el-input>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" v-if="itemShow" @click="onSub">确 定</el-button>
      <div v-else>
        <el-button type="primary" size="small" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="small" @click="onSubFun">确 定</el-button>
      </div>
    </span>
  </el-dialog>
  <el-dialog :title="'修改'+formTableUp.project" :close-on-click-modal="false" :visible.sync="dialogUpdata" width="400px" :before-close="handleClosegUp">
    <el-form :model="formTableUp" ref="ruleFormUp" label-width="100px">
      <el-form-item label="项目类别">
        {{formTableUp.project}}
      </el-form-item>
      <el-form-item label="项目">
        {{formTableUp.name}}
      </el-form-item>
      <el-form-item label="金额" prop="amount"  :rules="[{ required: true, message: '请输入金额', trigger: 'blur' }]">
        <el-input-number size="small" v-model.trim="formTableUp.amount" controls-position="right" :precision="2" :min="0" placeholder="请输入金额"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="handleClosegUp">取 消</el-button>
      <el-button type="primary" size="small" @click="onSubFungUp">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
import table2excel from '@/utils/export'
var vueParam = {
  data() {
    return {
      loading:true,
      form:{
        type: '',
      },
      dialogUpdata:false,
      indexUp:null,
      formTableUp:{},
      dialogVisible:false,
      itemShow:true,
      times: [],
      formTable:{
        sort:'',
        project:'',
        name:'',
        amount:'',
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now(); 
        }
      },
      tableHead:[
        { key: 'sort', value: '', title: '序号', type: 'text',width:'30px' },
        { key: 'project', value: '', title: '项目类别', type: 'text',width:'120px' },
        { key: 'name', value: '', title: '项目', type: 'text',width:'120px' },
        { key: 'amount', value: '', title: '金额', type: 'number',width:'100px' },
        { key: 'douYin', value: '', title: '抖音', type: 'number',width:'100px' },
        { key: 'xiaoChengXu', value: '', title: '小程序', type: 'number',width:'100px' },
        { key: 'huiDian', value: '', title: '汇点', type: 'number',width:'100px' },
        { key: 'meiTuan', value: '', title: '美团', type: 'number' ,width:'100px'},
        { key: 'xieCheng', value: '', title: '携程', type: 'number',width:'100px' },
        { key: 'ningMeng', value: '', title: '柠檬', type: 'number' ,width:'100px'},
        { key: 'naiSi', value: '', title: '奈斯', type: 'number',width:'100px' },
        { key: 'zhiKeTong', value: '', title: '直客通', type: 'number',width:'100px' },
        { key: 'weiTian', value: '', title: '维天', type: 'number',width:'100px' },
        { key: 'lengShan', value: '', title: '冷山', type: 'number',width:'100px' },
        { key: 'linSheng', value: '', title: '林盛', type: 'number' ,width:'100px'},
        { key: 'linXi', value: '', title: '霖希', type: 'number' ,width:'100px'},
        // { key: 'amount14', value: '', title: '卡类别', type: 'number',width:'100px' },
        // { key: 'amount15', value: '', title: '数量', type: 'number',width:'100px' },
      ],
      formDataList:[
        {name:'客房收入',item:'GuanShanSuAmount',project:'观山宿'},{name:'餐厅收入',item:'GuanShanSuCanTAmount',project:'观山宿'},{name:'其他收入',item:'GuanShanSuElseAmount',project:'观山宿'},
        {name:'房间收入',item:'ShuangQuanAmount',project:'双泉山庄'},{name:'会议室收入',item:'ShuangQuanMeetingAmount',project:'双泉山庄'},{name:'其他收入',item:'ShuangQuanElseAmount',project:'双泉山庄'},
        {name:'房间收入',item:'BanPoAmount',project:'半坡宿'},{name:'其他收入',item:'BanPoElseAmount',project:'半坡宿'},
        {name:'西关炖菜',item:'XiGuanDunAmount',project:'自营'},{name:'便利店',item:'BianLiDianAmount',project:'自营'},{name:'小东北',item:'XiaoDongBeiAmount',project:'自营'}
      ],
      tableHeadForm:[],
      tableData: []
    };
  },
  methods: {
    getList(){
      this.http.get("/api/Small_operate_dby/GetOperateList", {startdate:this.times[0],enddate:this.times[1]}, true).then((res) => {
        this.loading = false
        this.tableData = this.getTableData(res)
      });
    },
    getTableData(res){
      const sums = [];
      const sums1 = [];
      const sumszhyysr = [];
      this.tableHead.forEach((column, index) => {
        if (index === 0||index == 1||index==2) {
          return;
        }
        const values = []
        const values1 = []
        const valueszhyysr = []
        res.forEach(item => {
          if(item.name!='' && item.name!='小计' && ['总合计','酒店合计','综合营业收入'].indexOf(item.project)==-1){
            values.push(Number(item[column.key]))
          }
          if(item.name!='' && item.name!='小计'&&item.sort == 1){
            values1.push(Number(item[column.key]))
          }
          if(item.name!='' && item.name!='小计'&&(item.sort == 1 || item.sort == 2 || item.sort == 3 || item.sort == 4 || item.sort == 5)){
            valueszhyysr.push(Number(item[column.key]))
          }
        });
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
        if (!values1.every(value => isNaN(value))) {
          sums1[index] = values1.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
        if (!valueszhyysr.every(value => isNaN(value))) {
          sumszhyysr[index] = valueszhyysr.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });
      let leng = res.length-1
      let leng1 = 0
      let lenzhyysr = 0
      res.forEach((_)=>{
        if(_.sort == 1){
          leng1+=1
        }
        if(_.sort == 1 || _.sort == 2 || _.sort == 3 || _.sort == 4 || _.sort == 5){
          lenzhyysr+=1
        }
      })
      this.tableHead.map((v,i)=>{
        if(i >= 3){
          // 总计
          res[leng][v.key] = sums[i].toFixed(2)
          // 滑雪收入 小计
          res[leng1-1][v.key] = sums1[i].toFixed(2)
          // 综合营业收入 小计
          res[lenzhyysr][v.key] = sumszhyysr[i].toFixed(2)
        }
      })
      return res
    },
    // 确认修改
    handleClick(scope){
      if(this.times.length && this.times[0]==this.times[1]){
        this.formTableUp = JSON.parse(JSON.stringify(scope.row))
        this.indexUp = scope.$index
        this.dialogUpdata = true
      }else{
        this.$message({ message: '请选择开始日期和结束日期，并且在同一天才能进行修改', type: 'warning'});
        return
      }
    },
    // 提交修改数据
    onSubFungUp(){
      this.$refs.ruleFormUp.validate((valid) => {
        if (valid) {
          const params = {
            Date:this.times[0]
          }
          let a = this.formDataList.filter(v=> {return v.name==this.formTableUp.name && v.project==this.formTableUp.project} )
          if(a.length){
            params[`${a[0].item}`]= this.formTableUp.amount
            this.http.post("/api/Small_operate_dby/updateoperate", params, true).then((r) => {
             if(r.message){
              this.$message({ message:r.message, type: 'warning'});
             }else{
              this.handleClosegUp()
              this.getList()
             }
            });
          }else{
            this.tableData[this.indexUp].amount = JSON.parse(JSON.stringify(this.formTableUp.amount))
            this.handleClosegUp()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 关闭修改弹窗
    handleClosegUp(){
      this.formTableUp = {}
      this.indexUp = null
      this.dialogUpdata = false
    },
    // 关闭新增弹窗
    handleClose(){
      this.tableHeadForm = this.tableHeadForm.map(v=>{
        v.value = ''
        return v
      })
      this.formTable = {}
      this.form.type = ''
      this.itemShow = true
      this.dialogVisible = false
    },
    // 选择项目类别
    onSub(){
      if(this.form.type){
        this.itemShow = false
      }else{
        this.$message({ message: '请选择项目类别', type: 'warning'});
      }
    },
    // 新增table数据
    onSubFun(){
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.tableHeadForm.map((_)=>{
            if(_.value){
              this.formTable[_.key] = _.value
            }
          })
          this.formTable.project = {1:'联营',2:"赛事服务费/广告费等"}[this.form.type]
          if(!this.formTable.name){
            return this.$message({ message: '请输入项目', type: 'warning'});
          }
          var str = 0
          var i = 0
          this.tableData.map((v,ind)=>{
            if(v.project == this.formTable.project){
              if(!i){
                i = ind
              }
              str+=1
            }
          })
          this.tableData.splice((i+str-1),0,{...this.formTable,sort:this.formTable.project == '联营'?'8':'9'})
          this.handleClose()
          this.tableData = this.getTableData(this.tableData)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // table row更改颜色
    tableRowClassName({row, rowIndex}) {
      if (row.name == '小计') {
        return 'xj-row';
      }else if(row.project == '总合计' || row.project == '酒店合计' || row.project == '综合营业收入'){
        return 'zs-row';
      }
      return '';
    },
    // 导出
    exportToExcel(){
      const groupData = this.setrowspans(JSON.parse(JSON.stringify(this.tableData)))
      table2excel({
        column:this.tableHead,
        data: groupData,
        excelName: '东北亚营业日报',
        captionName: '2023-2024雪期总收入',
      })
    },
    setrowspans(arrData) {
      arrData.forEach(v => {
        v.rowspan = 1
        v.rowspanNum = 1
      })
      for (let i = 0; i < arrData.length; i++) {
        for (let j = i + 1; j < arrData.length; j++) {
          if (arrData[i].project !== '' && arrData[i].project === arrData[j].project) {
            arrData[i].rowspan++
            arrData[j].rowspan--
            delete arrData[j].project
          }
        }
        i = i + arrData[i].rowspan - 1
      }
      for (let i = 0; i < arrData.length; i++) {
        if(arrData[i].sort == '综合营业收入' || arrData[i].sort == '酒店合计' || arrData[i].sort == '总合计'){
          arrData[i].sort = ''
        }
        for (let j = i + 1; j < arrData.length; j++) {
          if (arrData[i].sort !== '' && arrData[i].sort === arrData[j].sort) {
            arrData[i].rowspanNum++
            arrData[j].rowspanNum--
            delete arrData[j].sort
          }
        }
        i = i + arrData[i].rowspanNum - 1
      }
      return arrData
    },
    /**表格合并单元格 */
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (row.project == "综合营业收入"||row.project == "酒店合计"||row.project == "总合计") {
        if (columnIndex == 0) {
          return [1, 3];
        } else if (columnIndex === 1) {
          return [0, 0];
        } else if (columnIndex === 2) {
          return [0, 0];
        }
      }
      if (columnIndex === 0) {
        // 合并第一列
        const _row = this.flitterData(this.tableData,column).one[rowIndex];
        const _col = _row > 0 ? 1 : 2;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      if (columnIndex === 1) {
        // 合并第二列
        const _row = this.flitterData(this.tableData,column).two[rowIndex];
        const _col = _row > 0 ? 1 : 2;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      if (columnIndex === 2) {
        // 合并第三列
        const _row2 = this.flitterData(this.tableData,column).three[rowIndex];
        const _col2 = _row2 > 0 ? 1 : 2;
        return {
          rowspan: _row2,
          colspan: _col2,
        };
      }
    },
    // table相同的数据合并 前三列
    flitterData (arr,column) {
      let spanOneArr = [];
      let concatOne = 0;
      
      let spanTwoArr = [];
      let concatTwo = 0;

      let spanThreeArr = [];
      let concatThree = 0;

      arr.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1);
          spanTwoArr.push(1);
        } else {
          let field1 = column.property
          if (item[field1] === arr[index - 1][field1]) {
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          }
          let field2 = column.property
          if (
            item[field1] === arr[index - 1][field1] &&
            item[field2] === arr[index - 1][field2]
          ) {
            spanTwoArr[concatTwo] += 1;
            spanTwoArr.push(0);
          } else {
            spanTwoArr.push(1);
            concatTwo = index;
          }
          let field3 = column.property
          if (item[field1] === arr[index - 1][field1] &&
            item[field2] === arr[index - 1][field2] &&
            item[field3] === arr[index - 1][field3]) {
            spanThreeArr[concatThree] += 1;
            spanThreeArr.push(0);
          } else {
            spanThreeArr.push(1);
            concatThree = index;
          }
        }
      });
      return {
        one: spanOneArr,
        two: spanTwoArr,
        three: spanThreeArr,
      };
    },
    getSummaries(param) {
      const { columns,data } = param;
      // 总合计
      let num = 0
      const values = data.filter(item => {
        return item.name!='' && item.name!='小计' && ['总合计','酒店合计','综合营业收入'].indexOf(item.project)==-1
      });
      values.forEach((v, i) => {
        if(v.amount){
          num+=v.amount
        }
      });
      this.tableData[this.tableData.length-1].amount = num.toFixed(2)
      // // 1
      let num1 = 0
      let ind1 = null
      const values1 = data.filter((item,index) => {
        if(item.sort=='1'){
          ind1 = index
        }
        return item.sort=='1' && item.name!='' && item.name!='小计'
      });
      values1.forEach((v, i) => {
        if(v.amount){
          num1+=v.amount
        }
      });
      this.tableData[ind1].amount = num1.toFixed(2)
      // // 8
      let num8 = 0
      let ind8 = null
      const values8 = data.filter((item,index) => {
        if(item.sort=='8'){
          ind8 = index
        }
        return item.sort=='8' && item.name!='' && item.name!='小计'
      });
      values8.forEach((v, i) => {
        if(v.amount){
          num8+=v.amount
        }
      });
      this.tableData[ind8].amount = num8.toFixed(2)
       // // 9
      let num9 = 0
      let ind9 = null
      const values9 = data.filter((item,index) => {
        if(item.sort=='9'){
          ind9 = index
        }
        return item.sort=='9' && item.name!='' && item.name!='小计'
      });
      values9.forEach((v, i) => {
        if(v.amount){
          num9+=v.amount
        }
      });
      this.tableData[ind9].amount = num9.toFixed(2)
      return [];
    },
    getDate() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      var hour = " 00:00:00"; //默认时分秒 如果传给后台的格式为年月日时分秒，就需要加这个，如若不需要，此行可忽略
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}${hour}`;//
      return defaultDate;
    }
  },
  created() {
    const time = this.getDate()
    this.times = [time,time]
    this.tableHeadForm = this.tableHead.slice(2)
    this.getList()
  },
};
export default vueParam;
</script>
<style lang="less" scoped>
.divSea{
  min-height: 80vh;
  padding:20px 20px 0 20px;
  .tableDiv{
    margin-top:10px;
    height: calc(100vh - 180px);
  }
}
.container {
  display: flex;
  justify-content: space-between;
}

.item {
  width: 50%;
}
</style>
<style>
  .el-table .xj-row {
    background: oldlace;
  }
  .el-table .zs-row { 
    background: #f0f9eb;
  }
</style>
